package com.wr.auth.common.service;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSONObject;
import com.wr.api.system.service.RemoteSystemService;
import com.wr.auth.common.constants.WeChatConstants;
import com.wr.auth.common.utils.WxBizDataCrypt;
import com.wr.auth.domain.wx.AppletLogin;
import com.wr.auth.domain.wx.GetWxWebCode;
import com.wr.auth.domain.wx.UserWxLetInfo;
import com.wr.api.system.domain.LoginUser;
import com.wr.api.system.domain.SysUserWxBo;
import com.wr.common.core.exception.ServiceException;
import com.wr.common.core.utils.BeanUtils;
import com.wr.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MyPC
 */
@Component
public class WeChatService {

    @Autowired
    private WeChatConstants weChatConstants;

    @Autowired
    private RemoteSystemService remoteUserService;


    public LoginUser getLoginUser(SysUserWxBo sysUserWxBo) {
        return remoteUserService.getUserInfoByWx(sysUserWxBo).getData();
    }

    public SysUserWxBo getUserWxInfoBo(String code, String type) {
        switch (type) {
            case "web":
                return getUserWxInfoBo(code, weChatConstants.getWebAppId(), weChatConstants.getWebAppSecret());
            case "gz":
                return getUserWxInfoBo(code, weChatConstants.getGzAppId(), weChatConstants.getGzAppSecret());
            default:
                throw new ServiceException("暂未开通此登录方式！");
        }
    }

    /**
     * 小程序授权登录
     *
     * @param appletLogin
     * @return
     */
    public SysUserWxBo getLetsWxUserInfoBo(AppletLogin appletLogin) {
        String info = WxBizDataCrypt.decrypt1(appletLogin.getEncryptedData(), appletLogin.getSessionKey(), appletLogin.getIv());
        UserWxLetInfo userWxLetInfo = JSONObject.parseObject(info, UserWxLetInfo.class);
        SysUserWxBo sysUserWxBo = BeanUtils.copyDataProp(userWxLetInfo, new SysUserWxBo());
        sysUserWxBo.setSex(userWxLetInfo.getGender());
        sysUserWxBo.setHeadImgUrl(userWxLetInfo.getAvatarUrl());
        return sysUserWxBo;
    }

    /**
     * 获取网站授权微信二维码
     *
     * @param getWxWebCode
     * @return
     */
    public String getWxWebCode(GetWxWebCode getWxWebCode) {
        //微信开放平台授权baseUrl
        String baseUrl = weChatConstants.getWxPublicUrl() +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "&href=%s" +
                "#wechat_redirect";
        String redirectUrl = weChatConstants.getWebRedirectUrl();
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String dataCode = "";
        if (StringUtils.isNotNull(getWxWebCode.getData())) {
            dataCode = new String(Base64.encode(getWxWebCode.getData().toString().getBytes()));
        }
        String href = "";
        if (StringUtils.isNotEmpty(getWxWebCode.getHref())) {
            href = "data:text/css;base64," + new String(Base64.encode(getWxWebCode.getHref().getBytes()));
        }
        String qrcodeUrl = String.format(
                baseUrl,
                weChatConstants.getWebAppId(),
                redirectUrl,
                //微信建议第三方带上这个参数 可随机为任何
                dataCode,
                href
        );
        return qrcodeUrl;
    }

    /**
     * 获取公众号登录页
     *
     * @param data
     * @return
     */
    public String getWxGzUrl(String data) {
        //微信开放平台授权baseUrl
        String baseUrl = weChatConstants.getWxGzAuthUrl() +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl = weChatConstants.getGzRedirectUrl();
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String dataCode = "";
        if (StringUtils.isNotEmpty(data)) {
            dataCode = new String(Base64.encode(data.getBytes()));
        }
        String gzUrl = String.format(
                baseUrl,
                weChatConstants.getGzAppId(),
                redirectUrl,
                //微信建议第三方带上这个参数 可随机为任何
                dataCode
        );
        return gzUrl;
    }


    private SysUserWxBo getUserWxInfoBo(String code, String appId, String appSecret) {
        //获取access_token
        Map<String, String> params = new HashMap<>(4);
        // APP_ID和APP_SERCRET需要根据实际情况进行传参
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        String openId = "";
        String accessToken = "";
//        String refreshToken = "";
        try {
//            String tokenRes = HttpUtil.sendGet(weChatConstants.getWzAuthUrl(), params);
//            JSONObject tokenJson = JSONObject.parseObject(tokenRes);
            //拿到access_token
//            openId = (String) tokenJson.get("openid");
//            accessToken = (String) tokenJson.get("access_token");
//            refreshToken = (String) tokenJson.get("refresh_token");
        } catch (Exception e) {
            throw new ServiceException("获取access_token失败，请检查配置信息");
        }
        //获取用户信息
        Map<String, String> body = new HashMap<>(2);
        // APP_ID和APP_SERCRET需要根据实际情况进行传参
        body.put("access_token", accessToken);
        body.put("openid", openId);
        try {
//            String infoRes = HttpUtil.sendGet(weChatConstants.getWxInfoUrl(), body);
//            UserWxWebInfo userWxWebInfo = JSONObject.parseObject(infoRes, UserWxWebInfo.class);
//            SysUserWxBo sysUserWxBo = BeanUtils.copyDataProp(userWxWebInfo, new SysUserWxBo());
//            sysUserWxBo.setOpenId(userWxWebInfo.getOpenid());
//            sysUserWxBo.setPrivilege(String.join(",", userWxWebInfo.getPrivilege()));
//            sysUserWxBo.setUnionId(userWxWebInfo.getUnionid());
//            return sysUserWxBo;
            return new SysUserWxBo();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取用户信息失败，请检查配置信息");
        }
    }
}
